<template>
  <div>
    <el-form
      :model="formData"
      inline
      style="display: flex; justify-content: flex-end; margin-top: 10px"
    >
      <el-form-item prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入广告标题"
        ></el-input>
      </el-form-item>
      <el-form-item prop="content">
        <el-input
          v-model="formData.content"
          placeholder="请输入广告内容"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <template slot-scope="scope">
          <el-button @click="search" type="primary">查找</el-button>
          <el-button
            @click="openDialog('创建', 'add', scope.row)"
            type="primary"
            >添加</el-button
          >
        </template>
      </el-form-item>
    </el-form>

    <el-table v-loading="tableLoading" :data="tableData" border>
      <el-table-column label="广告ID" prop="id"></el-table-column>
      <el-table-column label="广告标题" prop="name"></el-table-column>
      <el-table-column label="广告内容" prop="content"></el-table-column>
      <el-table-column label="广告图片" prop="url"></el-table-column>
      <el-table-column label="广告位置" prop="position"></el-table-column>
      <el-table-column label="活动链接" prop="link"></el-table-column>
      <el-table-column label="是否启用" prop="enabled">
        <template slot-scope="scope">
          <el-tag>{{ scope.row["enabled"] | tableFilter(options) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="openDialog('编辑', 'edit', scope.row)"
            type="primary"
            >编辑</el-button
          >
          <el-button size="mini" @click="deleteData(scope.row)" type="danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.page"
      :page-sizes="[10, 20, 30, 50, 100]"
      :page-size="pageInfo.limit"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
    >
    </el-pagination>

    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="500">
      <el-form
        ref="dialogForm"
        :model="dialogFormData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="广告标题" prop="name">
          <el-input v-model="dialogFormData.name"></el-input>
        </el-form-item>

        <el-form-item label="广告内容" prop="content">
          <el-input v-model.number="dialogFormData.content"></el-input>
        </el-form-item>

        <el-form-item label="广告图片" prop="url">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.200.251:8888/admin/storage/create"
            :show-file-list="false"
            :on-success="iconUrlSuccess"
            :headers="{ 'shopping-admin-token': token }"
          >
            <img
              v-if="dialogFormData.url"
              :src="dialogFormData.url"
              style="width: 100px"
            />
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
              style="
                width: 100px;
                height: 100px;
                border-radius: 10px;
                border: 2px dashed #ddd;
                line-height: 100px;
              "
            >
            </i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过1024kb
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="广告位置" prop="position">
          <el-input v-model.number="dialogFormData.position"></el-input>
        </el-form-item>

        <el-form-item label="活动链接" prop="link">
          <el-input v-model.number="dialogFormData.link"></el-input>
        </el-form-item>

        <el-form-item label="是否启用" prop="enabled">
          <el-select v-model="dialogFormData.enabled">
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="confirm" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import axios from "axios";
export default {
  name: "advertisingManagement",
  componentTitle: "广告管理",
  data() {
    return {
      token: sessionStorage.getItem("shopping-admin-token"),
      dialogVisible: false,
      dialogTitle: "创建",
      dialogType: "add",
      dialogFormData: {
        name: "",
        content: "",
        url: "",
        position: "",
        link: "",
        enabled: "",
      },
      formData: {
        name: "",
        content: "",
      },
      tableLoading: false,
      tableData: [],
      pageInfo: {
        page: 1,
        limit: 10,
        total: 0,
      },
      options: [
        { label: "启用", value: true },
        { label: "不启用", value: false },
      ],
      formRules: {
        name: [{ required: true, message: "请输入标题", trigger: "change" }],
        content: [{ required: true, message: "请输入内容", trigger: "change" }],
      },
    };
  },
  filters: {
    tableFilter(value, options) {
      let index = options.findIndex((item) => {
        return item.value === value;
      });
      if (index < 0) {
        return "----";
      } else {
        return options[index].label;
      }
    },
  },
  mounted() {
    this.search();
  },
  methods: {
    search() {
      this.tableLoading = true;
      axios({
        url: "http://192.168.200.251:8888/admin/ad/list",
        method: "get",
        params: {
          ...this.formData,
          page: this.pageInfo.page,
          limit: this.pageInfo.limit,
        },
        headers: {
          "shopping-admin-token": sessionStorage.getItem(
            "shopping-admin-token"
          ),
        },
      }).then((res) => {
        this.tableLoading = false;
        this.tableData = res.data.data.list;
        this.pageInfo.total = res.data.data.total;
      });
    },
    //打开dialog窗口
    openDialog(title, type, row) {
      console.log(row);
      this.dialogVisible = true;
      this.dialogType = type;
      this.dialogTitle = title;

      if (type === "edit") {
        this.$nextTick(() => {
          this.dialogFormData = Object.assign({}, row);
        });
      }
    },
    confirm() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          if (this.dialogType === "add") {
            this.addGoods();
          } else if (this.dialogType === "edit") {
            this.editGoods();
          }
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.$refs.dialogForm.resetFields();
      this.dialogVisible = false;
    },
    //上传图片成功的回调函数
    iconUrlSuccess(res, file) {
      this.dialogFormData.picUrl = res.data.url.replace(
        /localhost:8888/g,
        "192.168.200.251:8888"
      );
    },
    picUrlSuccess(res, file) {
      this.dialogFormData.iconUrl = res.data.url.replace(
        /localhost:8888/g,
        "192.168.200.251:8888"
      );
    },

    addGoods() {
      axios({
        url: "http://192.168.200.251:8888/admin/ad/create",
        method: "post",
        data: {
          ...this.dialogFormData,
        },
        headers: {
          "shopping-admin-token": sessionStorage.getItem(
            "shopping-admin-token"
          ),
        },
      }).then((res) => {
        if (res.data.errno === 0) {
          this.cancel();
          this.$notify.success({ title: "添加成功" });
          this.search();
        } else {
          this.$notify.error({ title: "添加失败" });
        }
      });
    },

    editGoods() {
      axios({
        url: "http://192.168.200.251:8888/admin/ad/update",
        method: "post",
        data: {
          ...this.dialogFormData,
        },
        headers: {
          "shopping-admin-token": sessionStorage.getItem(
            "shopping-admin-token"
          ),
        },
      }).then((res) => {
        if (res.data.errno === 0) {
          this.cancel();
          this.$notify.success({ title: "编辑成功" });
          this.search();
        } else {
          this.$notify.errno({ title: "编辑失败" });
        }
      });
    },

    deleteData(row) {
      axios({
        url: "http://192.168.200.251:8888/admin/ad/delete",
        method: "post",
        data: row,
        headers: {
          "shopping-admin-token": sessionStorage.getItem(
            "shopping-admin-token"
          ),
        },
      }).then((res) => {
        this.$notify.success({ title: "删除成功" });
        this.search();
      });
    },
    handleSizeChange(value) {
      this.pageInfo.limit = value;
      this.search();
    },
    handleCurrentChange(value) {
      this.pageInfo.page = value;
      this.search();
    },
  },
};
</script>
